import os
import sys
import time
import asyncio
import ccxt.pro as ccxtpro
from typing import Dict, List, Optional
from decimal import Decimal
from logs import setup_order_logger
from database_manager import DatabaseManager
from exchange_manager import ExchangeManager
from datetime import datetime
import json



# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.abspath(__file__))
if project_root not in sys.path:
    sys.path.append(project_root)


TRADING_SPREAD_THRESHOLD = 1.5  # 交易价差阈值2%
TRADE_DEPTH_MULTIPLIER = 1.5  # 交易深度倍数
DEFAULT_TRADE_VOLUME = 1  # 默认交易量
DEFAULT_LEVERAGE = 1  # 默认杠杆倍数
MONITOR_INTERVAL = 1  # 监控间隔，单位秒
ERROR_SLEEP_TIME = 5  # 发生错误时的等待时间，单位秒
MAX_DAILY_TRADES = 2  # 每天最多套利次数
MAX_DAYS_BETWEEN_TRADES = 3  # 同一交易对两次交易之间的最小天数
REDIS_KEY = "arbitrage:opportunities:current"  # Redis固定键名


class OrderMonitor:
    """
    订单监控器
    负责监控订单状态，执行平仓操作
    """
    def __init__(self):
        self.order_lock = asyncio.Lock()
        self.logger = setup_order_logger()
        self.trading_exchanges = {}
        self.db_manager = DatabaseManager()
        
        self.order_for_symbols = {}
        # 添加每日交易次数限制
        self.daily_trade_limits = {}  # 记录每个交易对每天的交易次数
        self.max_daily_trades = MAX_DAILY_TRADES     # 每个交易对每天最大交易次数
        self.last_reset_day = datetime.now().date() # 上次重置计数器的日期
        self.total_daily_trades = 0  # 账户当天的总交易次数
        self.symbol_last_trade = {}  # 记录每个交易对上次交易的时间
        


    async def init_exchange(self):
        """初始化交易所"""
        # 基础配置
        self.options = {
            'enableRateLimit': True,
            'options': {
                'defaultType': 'swap',
            }
        }
        
        # 支持的交易所列表
        exchange_ids = ['gateio', 'xt', 'bitget']

        # 创建交易所实例
        for exchange_id in exchange_ids:
            try:
                exchange_class = getattr(ccxtpro, exchange_id)
                self.trading_exchanges[exchange_id] = exchange_class(self.options)
                
                # 从环境变量获取API密钥
                api_key = os.getenv(f"{exchange_id.upper()}_API_KEY")
                secret_key = os.getenv(f"{exchange_id.upper()}_SECRET")
                password = os.getenv(f"{exchange_id.upper()}_PASSWORD")
                
                # 检查是否获取到API密钥
                if not api_key or not secret_key:
                    self.logger.error(f"无法获取 {exchange_id} 的API密钥，请检查.env文件")
                    continue

                # 设置API密钥
                exchange = self.trading_exchanges[exchange_id]
                exchange.apiKey = api_key
                exchange.secret = secret_key
                
                # 如果提供了password（某些交易所需要），则设置
                if password:
                    exchange.password = password
                    
                self.logger.info(f"交易所 {exchange_id} 初始化成功")
                
            except Exception as e:
                self.logger.error(f"初始化交易所 {exchange_id} 失败: {str(e)}")
                
        if not self.trading_exchanges:
            self.logger.error("没有成功初始化任何交易所")
            return False
            
        self.logger.info(f"成功初始化 {len(self.trading_exchanges)} 个交易所")
        return True

    async def check_diff_ranking_list(self):
        """从Redis检查价差排行榜"""
        while True:
            try:
                await asyncio.sleep(MONITOR_INTERVAL)
                
                # 从Redis获取排序后的价差排行榜
                redis_client = self.db_manager.get_redis_client()
                data = redis_client.get(REDIS_KEY)
                
                if not data:
                    self.logger.info("Redis中没有找到套利机会数据")
                    continue
                
                # 解析JSON数据
                sorted_diff_percents = json.loads(data)
                
                if not sorted_diff_percents:
                    self.logger.info("当前没有套利机会")
                    continue
                
                # 处理每个满足条件的套利机会
                tasks = []
                for symbol, opp in sorted_diff_percents.items():
                    # 检查是否已经在处理中，避免重复处理
                    if symbol in self.order_for_symbols:
                        continue
                        
                    if opp['price_diff'] >= TRADING_SPREAD_THRESHOLD:
                        # 为每个套利机会创建单独的任务
                        task = asyncio.create_task(self.check_order_book_depth(opp))
                        tasks.append(task)
                
                # 如果有任务，等待所有任务完成
                if tasks:
                    self.logger.info(f"发现 {len(tasks)} 个潜在套利机会，正在检查盘口深度")
                    await asyncio.gather(*tasks, return_exceptions=True)
                    
            except Exception as e:
                self.logger.error(f"检查价差排行榜时出错: {str(e)}")
                await asyncio.sleep(ERROR_SLEEP_TIME)  # 出错时等待一段时间再重试
    

    async def check_order_book_depth(self, opp: Dict):
        """检查盘口深度状态"""
        # 获取套利机会的详细信息
        symbol = opp['symbol']
        buy_exchange_id = opp['buy_exchange']
        sell_exchange_id = opp['sell_exchange']
        buy_price = Decimal(str(opp['buy_price']))
        sell_price = Decimal(str(opp['sell_price']))
        volume = Decimal(str(DEFAULT_TRADE_VOLUME))  # 默认交易量
        price_diff = opp['price_diff']  # 获取价差
        
        # 获取交易所实例
        buy_exchange = self.trading_exchanges.get(buy_exchange_id)
        sell_exchange = self.trading_exchanges.get(sell_exchange_id)
        
        if not buy_exchange or not sell_exchange:
            self.logger.error(f"无法获取交易所实例: 买入={buy_exchange_id}, 卖出={sell_exchange_id}")
            return
        
        try:
            # 使用并发获取盘口深度
            buy_order_book, sell_order_book = await asyncio.gather(
                buy_exchange.fetch_order_book(symbol, limit=300),
                sell_exchange.fetch_order_book(symbol, limit=300)
            )
            # 检查买入交易所的盘口深度 - 应该检查卖盘(asks)，因为我们是从卖盘买入
            buy_depth_ok = self._check_depth(buy_order_book, 'asks', buy_price, volume * Decimal(TRADE_DEPTH_MULTIPLIER))
            
            # 检查卖出交易所的盘口深度 - 应该检查买盘(bids)，因为我们是向买盘卖出
            sell_depth_ok = self._check_depth(sell_order_book, 'bids', sell_price, volume * Decimal(TRADE_DEPTH_MULTIPLIER))
            
            # 如果盘口深度满足交易量的1.5倍，并且实时价差大于TRADING_SPREAD_THRESHOLD，执行交易
            if buy_depth_ok and sell_depth_ok and price_diff > TRADING_SPREAD_THRESHOLD:
                self.logger.info(f"盘口深度满足要求，且价差大于阈值，准备执行套利交易: {symbol}")
                await self.execute_trade(opp)
            else:
                self.logger.warning(f"盘口深度或价差不满足条件: {symbol} - 买入深度: {buy_depth_ok}, 卖出深度: {sell_depth_ok}, 价差: {price_diff:.2f}%")
                
        except Exception as e:
            self.logger.error(f"检查盘口深度时出错: {str(e)}")


    def _check_depth(self, order_book: Dict, side: str, price: Decimal, volume: Decimal) -> bool:
        """
        检查盘口深度是否满足要求
        
        Args:
            order_book: 订单簿数据
            side: 盘口方向 (bids 买入 / asks 卖出)
            price: 目标价格
            volume: 所需交易量
            
        Returns:
            bool: 深度是否满足要求
        """
        return True
        try:
            total_volume = Decimal('0')
            for level in order_book[side]:
                level_price = Decimal(str(level[0]))
                level_volume = Decimal(str(level[1]))
                
                # 如果价格超出目标价格范围，停止检查
                # 买盘(bids)：我们愿意以不低于price的价格卖出
                # 卖盘(asks)：我们愿意以不高于price的价格买入
                if (side == 'bids' and level_price < price) or (side == 'asks' and level_price > price):
                    break
                    
                total_volume += level_volume
                if total_volume >= volume:
                    return True
                    
            return False
        except Exception as e:
            self.logger.error(f"计算盘口深度时出错: {str(e)}")
            return False


    async def check_balance(self, exchange_id: str, symbol: str, required_amount: Decimal, is_buy: bool) -> bool:
        """
        检查交易所余额是否足够
        
        Args:
            exchange_id: 交易所ID
            symbol: 交易对
            required_amount: 所需金额
            is_buy: 是否是买入交易所
            
        Returns:
            bool: 余额是否充足
        """
        exchange = self.trading_exchanges.get(exchange_id)
        if not exchange:
            self.logger.error(f"无法获取交易所实例: {exchange_id}")
            return False
            
        try:
            # 获取账户余额
            balance = await exchange.fetch_balance()
            
            # 解析交易对获取基础货币
            base_currency = symbol.split('/')[0]
            quote_currency = symbol.split('/')[1]
            
            # 获取最新价格
            ticker = await exchange.fetch_ticker(symbol)
            current_price = Decimal(str(ticker['last']))
            
            # 检查是否有足够的余额
            if is_buy:
                # 买入交易所需要检查quote_currency余额(如USDT)
                available = Decimal(str(balance.get(quote_currency, {}).get('free', 0)))
                required = required_amount * current_price
                
                if available < required:
                    self.logger.warning(f"{exchange_id} 的 {quote_currency} 余额不足: 可用 {available:.8f}, 需要 {required:.8f}")
                    return False
            else:
                # 卖出交易所需要检查base_currency余额(如BTC)
                available = Decimal(str(balance.get(base_currency, {}).get('free', 0)))
                
                if available < required_amount:
                    self.logger.warning(f"{exchange_id} 的 {base_currency} 余额不足: 可用 {available:.8f}, 需要 {required_amount:.8f}")
                    return False
                    
            self.logger.info(f"{exchange_id} 余额充足，可以执行交易")
            return True
            
        except Exception as e:
            self.logger.error(f"检查 {exchange_id} 余额时出错: {str(e)}")
            return False


    async def _reset_daily_limits_if_needed(self):
        """检查并在需要时重置每日交易限制"""
        current_date = datetime.now().date()
        if current_date > self.last_reset_day:
            self.logger.info(f"新的一天开始，重置所有交易对的每日交易限制")
            self.daily_trade_limits = {}
            self.total_daily_trades = 0  # 重置账户总交易次数
            self.last_reset_day = current_date
            
    async def _check_daily_limit(self, symbol: str) -> bool:
        """
        检查交易对是否达到每日交易限制
        
        Args:
            symbol: 交易对符号
            
        Returns:
            bool: True表示未达到限制，可以交易；False表示已达到限制
        """
        # 先检查是否需要重置限制
        await self._reset_daily_limits_if_needed()
        
        # 检查账户总交易次数是否达到上限
        if self.total_daily_trades >= MAX_DAILY_TRADES:
            self.logger.warning(f"账户今日已达到最大交易次数限制 ({MAX_DAILY_TRADES}次)，跳过交易")
            return False
        
        # 检查当前交易对的交易次数
        current_count = self.daily_trade_limits.get(symbol, 0)
        if current_count >= 1:  # 每个交易对每天最多交易1次
            self.logger.warning(f"{symbol} 今日已交易过，跳过交易")
            return False
        
        # 检查交易对是否满足3天间隔限制
        current_time = datetime.now().timestamp()
        last_trade_time = self.symbol_last_trade.get(symbol, 0)
        days_since_last_trade = (current_time - last_trade_time) / (24 * 3600)
        
        if days_since_last_trade < MAX_DAYS_BETWEEN_TRADES:
            self.logger.warning(f"{symbol} 距离上次交易仅过去 {days_since_last_trade:.1f} 天，不满足 {MAX_DAYS_BETWEEN_TRADES} 天间隔要求，跳过交易")
            return False
        
        return True

    async def execute_trade(self, opp: Dict):
        """执行套利交易并将订单信息存入数据库"""
        symbol = opp['symbol']
        buy_exchange_id = opp['buy_exchange']
        sell_exchange_id = opp['sell_exchange']
        buy_price = Decimal(str(opp['buy_price']))
        sell_price = Decimal(str(opp['sell_price']))
        volume = Decimal(str(DEFAULT_TRADE_VOLUME))  # 默认交易量
        leverage = DEFAULT_LEVERAGE  # 默认杠杆倍数
        price_diff = opp['price_diff']  # 价差

        # 获取交易所实例
        buy_exchange = self.trading_exchanges.get(buy_exchange_id)
        sell_exchange = self.trading_exchanges.get(sell_exchange_id)

        if not buy_exchange or not sell_exchange:
            self.logger.error(f"无法获取交易所实例: 买入={buy_exchange_id}, 卖出={sell_exchange_id}")
            return

        try:
            # 检查是否达到交易限制
            if not await self._check_daily_limit(symbol):
                return None
                
            # 检查余额是否足够
            buy_balance_ok = await self.check_balance(buy_exchange_id, symbol, volume, True)
            sell_balance_ok = await self.check_balance(sell_exchange_id, symbol, volume, False)
            
            if not buy_balance_ok or not sell_balance_ok:
                self.logger.error(f" {buy_exchange_id} 或 {sell_exchange_id} 余额检查失败，无法执行交易: {symbol}")
                return None
            
            # 设置杠杆倍数
            await buy_exchange.set_leverage(leverage, symbol)
            await sell_exchange.set_leverage(leverage, symbol)

            # 在买入交易所下单
            buy_order = await buy_exchange.create_order(
                symbol=symbol,
                type='limit',
                side='buy',
                amount=float(volume),
                price=float(buy_price)
            )

            # 在卖出交易所下单
            sell_order = await sell_exchange.create_order(
                symbol=symbol,
                type='limit',
                side='sell',
                amount=float(volume),
                price=float(sell_price)
            )

            # 记录订单信息
            self.logger.info(f"买入订单: {buy_order['id']} - {symbol} - 价格: {buy_price} - 数量: {volume} - 杠杆: {leverage}x")
            self.logger.info(f"卖出订单: {sell_order['id']} - {symbol} - 价格: {sell_price} - 数量: {volume} - 杠杆: {leverage}x")
            
            # 更新交易对的每日交易计数
            self.daily_trade_limits[symbol] = self.daily_trade_limits.get(symbol, 0) + 1
            # 更新账户总交易次数
            self.total_daily_trades += 1
            # 更新交易对的最后交易时间
            self.symbol_last_trade[symbol] = datetime.now().timestamp()
            
            self.logger.info(f"{symbol} 交易记录更新: 今日第 {self.daily_trade_limits[symbol]} 次，账户今日总交易: {self.total_daily_trades}/{MAX_DAILY_TRADES}，下次可交易时间: {datetime.fromtimestamp(self.symbol_last_trade[symbol] + MAX_DAYS_BETWEEN_TRADES * 24 * 3600).strftime('%Y-%m-%d %H:%M:%S')}")
            
            # 生成唯一订单ID
            trade_id = f"{int(time.time())}_{symbol.replace('/', '_')}"
            
            # 创建订单数据
            order_data = {
                'trade_id': trade_id,
                'symbol': symbol,
                'buy_exchange': buy_exchange_id,
                'sell_exchange': sell_exchange_id,
                'buy_order_id': buy_order['id'],
                'sell_order_id': sell_order['id'],
                'buy_price': float(buy_price),
                'sell_price': float(sell_price),
                'amount': float(volume),
                'leverage': leverage,
                'price_diff': float(price_diff),
                'status': 'OPEN',
                'create_time': time.time(),
                'update_time': time.time(),
                'close_time': None,
                'close_reason': None,
                'profit': float((sell_price - buy_price) * volume)
            }
            
            # 将订单信息保存到数据库
            await self._save_trade_to_db(order_data)
            
            # 添加到内存中的订单字典，用于实时监控
            async with self.order_lock:
                self.order_for_symbols[symbol] = {
                    'trade_id': trade_id,
                    'buy_exchange_id': buy_exchange_id,
                    'sell_exchange_id': sell_exchange_id,
                    'buy_order': buy_order,
                    'sell_order': sell_order,
                    'price_diff': float(price_diff),
                    'original_price_diff': float(price_diff),  # 保存原始价差，用于后续计算
                    'order_create_time': time.time()
                }

            return trade_id
            
        except Exception as e:
            self.logger.error(f"下单失败: {str(e)}")
            return None

    async def _save_trade_to_db(self, order_data: Dict):
        """将交易订单保存到数据库"""
        try:
            # 使用数据库管理器保存订单
            await self.db_manager.save_arbitrage_order(order_data)
            self.logger.info(f"订单 {order_data['trade_id']} 已保存到数据库")
        except Exception as e:
            self.logger.error(f"保存订单到数据库失败: {str(e)}")


    async def _update_trade_status_in_db(self, trade_id: str, status: str, close_reason: str = None, 
                                    close_time: float = None, actual_profit: float = None,
                                    close_buy_price: float = None, close_sell_price: float = None):
        """更新数据库中的交易状态"""
        try:
            # 准备更新数据
            update_data = {
                'status': status,
                'update_time': time.time()
            }
            
            if close_reason:
                update_data['close_reason'] = close_reason
            
            if close_time:
                update_data['close_time'] = close_time
                
            if actual_profit is not None:
                update_data['actual_profit'] = actual_profit
                
            if close_buy_price:
                update_data['close_buy_price'] = close_buy_price
                
            if close_sell_price:
                update_data['close_sell_price'] = close_sell_price
            
            # 使用数据库管理器更新订单状态
            await self.db_manager.update_arbitrage_order(trade_id, update_data)
            self.logger.info(f"订单 {trade_id} 状态已更新为 {status}")
        except Exception as e:
            self.logger.error(f"更新订单状态失败: {str(e)}")


    async def _should_close_position(self, original_price_diff: float, current_price_diff: float, order_age_hours: float) -> tuple[bool, str]:
        """
        检查是否满足平仓条件
        
        Args:
            original_price_diff: 原始价差百分比
            current_price_diff: 当前价差百分比
            order_age_hours: 订单存在时间（小时）
            
        Returns:
            tuple: (是否应该平仓, 平仓原因)
        """
        # 平仓决策
        should_close = False
        close_reason = ""
        
        # 1. 最高优先级：价格完全相同
        if abs(current_price_diff) < 0.01:
            should_close = True
            close_reason = "价格基本相同，优先平仓"
            
        # 2. 中等优先级：价差在0.2%以内且订单超过1天，且价差不再缩小或拉大超过0.2%
        elif abs(current_price_diff) <= 0.2 and order_age_hours >= 24 and abs(current_price_diff - original_price_diff) <= 0.2:
            should_close = True
            close_reason = "价差在0.2%以内且订单超过1天，价差稳定，执行平仓"
            
        # 3. 次中等优先级：价差缩小超过50%且订单超过12小时
        elif current_price_diff <= original_price_diff * 0.5 and order_age_hours >= 12:
            should_close = True
            close_reason = "价差缩小超过50%且订单超过12小时，执行平仓"
            
        # 4. 最低优先级：订单超过3天且价差没有明显缩小或缩小了0.2%的成本时平仓
        elif order_age_hours >= 72 and (current_price_diff >= original_price_diff - 0.2):
            should_close = True
            close_reason = "订单超过3天且价差未明显改善，执行平仓"
        
        return should_close, close_reason



    async def close_order(self, opp: Dict, close_reason: str, current_price_diff: float, order_create_time: float):
        """平仓操作并更新数据库状态"""
        symbol = opp['symbol']
        buy_exchange_id = opp['buy_exchange']
        sell_exchange_id = opp['sell_exchange']
        original_price_diff = opp['price_diff']  # 原始价差
        current_time = time.time()
        order_age_hours = (current_time - order_create_time) / 3600  # 订单年龄（小时）
        
        # 获取交易所实例
        buy_exchange = self.trading_exchanges.get(buy_exchange_id)
        sell_exchange = self.trading_exchanges.get(sell_exchange_id)
        
        if not buy_exchange or not sell_exchange:
            self.logger.error(f"无法获取交易所实例: 买入={buy_exchange_id}, 卖出={sell_exchange_id}")
            return False
        
        try:
            # 查找原始订单ID
            trade_id = None
            async with self.order_lock:
                if symbol in self.order_for_symbols:
                    trade_id = self.order_for_symbols[symbol].get('trade_id')
            
            # 获取当前买卖价格
            buy_ticker = await buy_exchange.fetch_ticker(symbol)
            sell_ticker = await sell_exchange.fetch_ticker(symbol)
            
            current_buy_price = Decimal(str(buy_ticker['last']))
            current_sell_price = Decimal(str(sell_ticker['last']))
            
            # 执行平仓
            self.logger.info(f"开始平仓: {symbol} - 原因: {close_reason}")
            self.logger.info(f"原始价差: {original_price_diff:.2f}%, 当前价差: {current_price_diff:.2f}%, 订单年龄: {order_age_hours:.1f}小时")
            
            # 反向下单平仓
            volume = Decimal(str(DEFAULT_TRADE_VOLUME))
            
            # 在买入交易所卖出平仓
            try:
                close_buy_order = await buy_exchange.create_order(
                    symbol=symbol,
                    type='market',  # 使用市价单快速平仓
                    side='sell',
                    amount=float(volume)
                )
                self.logger.info(f"买入交易所反向卖出成功: {close_buy_order['id']}")
            except Exception as e:
                self.logger.error(f"买入交易所平仓失败: {str(e)}")
                return False
            
            # 在卖出交易所买入平仓
            try:
                close_sell_order = await sell_exchange.create_order(
                    symbol=symbol,
                    type='market',  # 使用市价单快速平仓
                    side='buy',
                    amount=float(volume)
                )
                self.logger.info(f"卖出交易所反向买入成功: {close_sell_order['id']}")
            except Exception as e:
                self.logger.error(f"卖出交易所平仓失败: {str(e)}")
                return False
            
            self.logger.info(f"平仓完成 - 买入交易所反向卖出: {close_buy_order['id']}, 卖出交易所反向买入: {close_sell_order['id']}")
            
            # 计算实际利润
            actual_profit = float(((current_sell_price - current_buy_price) * volume))
            
            # 更新数据库中的订单状态
            if trade_id:
                await self._update_trade_status_in_db(
                    trade_id=trade_id,
                    status='CLOSED',
                    close_reason=close_reason,
                    close_time=current_time,
                    actual_profit=actual_profit,
                    close_buy_price=float(current_buy_price),
                    close_sell_price=float(current_sell_price)
                )
            
            # 从活跃订单字典中移除
            async with self.order_lock:
                if symbol in self.order_for_symbols:
                    del self.order_for_symbols[symbol]
            
            return True
            
        except Exception as e:
            self.logger.error(f"平仓操作失败: {str(e)}")
            return False


    async def _monitor_exchange_prices(self, exchange_id: str, exchange, symbols: List[str]):
        """监控单个交易所的价格并更新相关交易对数据"""
        self.logger.info(f"开始监控交易所 {exchange_id} 的价格，交易对: {symbols}")

        # 检查交易所是否支持 watchTickers 方法
        func_name = 'watchTickers'
        if not exchange.has[func_name]:
            print(f"{exchange_id} 不支持 {func_name}")
            return
        

        while True:
            try:
                # 使用 watchTickers 监控价格
                tickers = await getattr(exchange, func_name)(symbols, params={})
                
                async with self.order_lock:
                    for symbol, ticker in tickers.items():
                        if symbol in self.order_for_symbols:
                            order_info = self.order_for_symbols[symbol]
                            last_price = ticker.get('last')
                            
                            if last_price is not None:
                                # 更新对应交易所的最新价格
                                if order_info['buy_exchange_id'] == exchange_id:
                                    order_info['current_buy_price'] = last_price
                                    order_info['buy_timestamp'] = exchange.milliseconds()
                                    self.logger.debug(f"更新 {symbol} 买入价格: {last_price}")
                                
                                if order_info['sell_exchange_id'] == exchange_id:
                                    order_info['current_sell_price'] = last_price
                                    order_info['sell_timestamp'] = exchange.milliseconds()
                                    self.logger.debug(f"更新 {symbol} 卖出价格: {last_price}")
                                
                                # 只有同时有买入和卖出价格时才进行计算
                                if 'current_buy_price' in order_info and 'current_sell_price' in order_info:
                                    current_buy_price = order_info['current_buy_price']
                                    current_sell_price = order_info['current_sell_price']
                                    
                                    # 计算当前价差
                                    price_diff = abs((current_sell_price - current_buy_price) / current_buy_price * 100)
                                    
                                    # 保存当前价差
                                    order_info['price_diff'] = price_diff
                                    self.logger.debug(f"更新 {symbol} 价差: {price_diff:.2f}%")
                                    
                                    # 检查是否满足平仓条件
                                    current_time = time.time()
                                    order_age_hours = (current_time - order_info['order_create_time']) / 3600
                                    
                                    # 获取原始价差
                                    original_price_diff = order_info.get('original_price_diff', order_info.get('price_diff', 0))
                                    
                                    should_close, close_reason = await self._should_close_position(
                                        original_price_diff,  # 原始价差
                                        price_diff,          # 当前价差
                                        order_age_hours      # 订单年龄(小时)
                                    )
                                    
                                    # 如果满足平仓条件，执行平仓操作
                                    if should_close:
                                        self.logger.info(f"{symbol} 满足平仓条件: {close_reason}")
                                        
                                        opp = {
                                            'symbol': symbol,
                                            'buy_exchange': order_info['buy_exchange_id'],
                                            'sell_exchange': order_info['sell_exchange_id'],
                                            'price_diff': original_price_diff  # 使用原始价差
                                        }
                                        
                                        await self.close_order(
                                            opp,
                                            close_reason,
                                            price_diff,
                                            order_info['order_create_time']
                                        )
                                
        
                
            except Exception as e:
                self.logger.error(f"监控交易所 {exchange_id} 价格时出错: {str(e)}")
                if hasattr(exchange, 'unwatchTickers'):
                    await exchange.unwatchTickers()
                
                # 短暂等待后重试
                await asyncio.sleep(ERROR_SLEEP_TIME)
                
                # 更新需要监控的交易对列表 - 检查哪些交易对仍需监控
                updated_symbols = []
                async with self.order_lock:
                    for symbol in symbols:
                        if symbol in self.order_for_symbols:
                            order_info = self.order_for_symbols[symbol]
                            if (order_info['buy_exchange_id'] == exchange_id or 
                                order_info['sell_exchange_id'] == exchange_id):
                                updated_symbols.append(symbol)
                
                # 如果没有需要监控的交易对了，停止任务
                if not updated_symbols:
                    self.logger.info(f"交易所 {exchange_id} 没有需要监控的交易对，停止监控")
                    break
                
                # 更新交易对列表
                symbols = updated_symbols
                
                # 重新尝试监控
                continue
    

    async def monitor_order_status(self):
        """监控订单状态和价格变化"""
        # 获取所有需要监控的交易对
        symbols_to_watch = list(self.order_for_symbols.keys())
        if not symbols_to_watch:
            self.logger.info("没有需要监控的交易对")
            return
        
        # 确定需要监控的交易所
        exchanges_to_monitor = set()
        exchange_symbols = {}
        
        # 为每个交易所收集需要监控的交易对
        for symbol, order_info in self.order_for_symbols.items():
            buy_exchange_id = order_info['buy_exchange_id']
            sell_exchange_id = order_info['sell_exchange_id']
            
            # 添加到需要监控的交易所集合
            exchanges_to_monitor.add(buy_exchange_id)
            exchanges_to_monitor.add(sell_exchange_id)
            
            # 为每个交易所准备需要监控的交易对列表
            if buy_exchange_id not in exchange_symbols:
                exchange_symbols[buy_exchange_id] = []
            if sell_exchange_id not in exchange_symbols:
                exchange_symbols[sell_exchange_id] = []
            
            exchange_symbols[buy_exchange_id].append(symbol)
            exchange_symbols[sell_exchange_id].append(symbol)
        
        tasks = []
        
        # 只为涉及到的交易所创建监控任务
        for exchange_id in exchanges_to_monitor:
            exchange = self.trading_exchanges.get(exchange_id)
            if exchange:
                symbols = exchange_symbols[exchange_id]
                task = asyncio.create_task(
                    self._monitor_exchange_prices(exchange_id, exchange, symbols)
                )
                tasks.append(task)
        
        
        # 运行所有任务
        await asyncio.gather(*tasks)
        


    async def run(self):

        print("开始运行订单监控器")
        """运行订单监控器"""
        try:
            # 初始化交易所
            init_result = await self.init_exchange()
            if init_result is False:
                self.logger.error("交易所初始化失败，无法启动订单监控器")
                return
                
            self.logger.info("订单监控器启动成功")
            
            # 创建任务列表
            tasks = []
            
            # 添加价差排行榜监控任务
            diff_task = asyncio.create_task(self.check_diff_ranking_list())
            tasks.append(diff_task)
            
            # 添加订单状态监控任务
            if self.order_for_symbols:
                order_task = asyncio.create_task(self.monitor_order_status())
                tasks.append(order_task)
                self.logger.info(f"开始监控 {len(self.order_for_symbols)} 个活跃订单")
            
            # 等待所有任务完成或出错
            await asyncio.gather(*tasks, return_exceptions=True)
            
        except Exception as e:
            self.logger.error(f"订单监控器运行出错: {str(e)}")
        finally:
            # 关闭所有交易所连接
            for exchange_id, exchange in self.trading_exchanges.items():
                try:
                    if hasattr(exchange, 'close'):
                        await exchange.close()
                        self.logger.info(f"关闭交易所连接: {exchange_id}")
                except Exception as e:
                    self.logger.error(f"关闭交易所 {exchange_id} 连接失败: {str(e)}")
            
            self.logger.info("订单监控器已停止运行")

   
    

   